<?php
/**
 * 用户服务类
 * @author bcxgame
 * @version 1.0
 */
namespace app\common\service;
use app\common\library\Auth;
use app\common\exception\User as UserException;
use app\common\library\Jwt;
use app\common\model\Members as UserModel;
use Config;
use http\Http;
use app\common\exception\SmsCode as SmsCodeException;
use Cache;
use think\Db;

class User
{
	/**
	 * 异常类名容器
	 * @var array
	 */
	private $_exceptions = [
		'user' => '\app\common\exception\User',
	];

	/**
	 * 用户注册
	 */
	public function register($data, $auth = NULL)
	{
		if (!$data) {
			return false;
		}
//        $codeKey = 'register:'.$data['phone'];
//        $codes = Cache::store('redis')->handler()->get($codeKey);
//        if (!$codes) {
//          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_EXPIRE),SmsCodeException::E_CODE_EXPIRE);
//        } else if ($codes != $data['phone_code']) {
//          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_NO),SmsCodeException::E_CODE_NO);
//        }
		if (is_null($auth)) {
			$auth = Auth::instance();
		}

		// 检测用户名或邮箱、手机号是否存在
        if (UserModel::getByPhone($data['phone'])) {
            exception(UserException::getErrorMsg(UserException::E_PHONE_EXISTS), UserException::E_PHONE_EXISTS, $this->_exceptions['user']);
        }
       
        if(isset($data['code']) && $data['code'] != ''){
        	$userId = $auth->register($data['phone'], $data['password'], ['re_code' => $data['code']]);
        }else{
			$userId = $auth->register($data['phone'], $data['password']);
        }

        if ($userId == -1) {
          exception(UserException::getErrorMsg(UserException::E_CODE), UserException::E_CODE, $this->_exceptions['user']);
        }

		if (!$userId) {
			exception(UserException::getErrorMsg(UserException::E_ADD_FAIL), UserException::E_ADD_FAIL, $this->_exceptions['user']);
		}

		// 生成JWT
		$token = Jwt::createToken($userId);
		if (!$token) {
			exception(UserException::getErrorMsg(UserException::E_JWT_ERROR), UserException::E_JWT_ERROR, $this->_exceptions['user']);
		}

		return ['auth' => $token, 'user_id' => $userId];
	}

	/**
	 * 用户登录
	 */
	public function login($data, $auth = NULL)
	{
      if (!$data) {
          return false;
      }
      if (is_null($auth)) {
        $auth = Auth::instance();
      }

      // 查询最大登录次数
      if ($auth->member_id) {
          $userInfo = $auth->getUser();
      } else {
          $userInfo = UserModel::getByPhone($data['phone']);
      }

      if (!$userInfo) {
          exception(UserException::getErrorMsg(UserException::E_PASSWORD), UserException::E_PASSWORD, $this->_exceptions['user']);
      }

      // 对比日期
      if (strtotime(date('Y-m-d')) == $userInfo->login_failure_date && $userInfo->login_failure > Config::get('max_login_failures')) {
          exception(UserException::getErrorMsg(UserException::E_MAX_LOGIN), UserException::E_MAX_LOGIN, $this->_exceptions['user']);
      }

      $userId = $auth->login($data['phone'], $data['password']);
      if (!$userId) {
          exception($auth->getError(), UserException::E_PASSWORD, $this->_exceptions['user']);
      }

      // 生成JWT
      $token = Jwt::createToken($userId);
      if (!$token) {
          exception(UserException::getErrorMsg(UserException::E_JWT_ERROR), UserException::E_JWT_ERROR, $this->_exceptions['user']);
      }

      // 获取redis中的token
      $loginToken = Jwt::getColumn($token, 'uid');
      $updateId = UserModel::where('member_id', $userInfo->member_id)->update(['jwt_token' => $loginToken]);
      if ($updateId === false) {
          exception(UserException::getErrorMsg(UserException::E_JWT_ERROR), UserException::E_JWT_ERROR, $this->_exceptions['user']);
      }

      return ['auth' => $token, 'user_id' => $userId];
	}

	public function forgetPwd($data)
	{
        $codeKey = 'forgetPwd:'.$data['phone'];
        $codes = Cache::store('redis')->handler()->get($codeKey);
        if (!$codes) {
          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_EXPIRE),SmsCodeException::E_CODE_EXPIRE);
        } else if ($codes != $data['phone_code']) {
          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_NO),SmsCodeException::E_CODE_NO);
        }

		$membersModel = model('common/Members');
		$info = $membersModel->fetch(['phone' => $data['phone']]);
		if(empty($info)){
			exception('手机号码未注册', UserException::E_NOT_EXISTS, 'app\common\exception\User');
		}

		$auth = Auth::instance();
		$res = $membersModel->editData(['phone' => $data['phone']], ['password' => $auth->getEncryptPassword($data['password'], $info['salt'])]);
	}

	/**
	 * 我的推荐
	 */
	public function recommend($auth, $page, $limit)
	{
		$RecommendModel = model('common/Recommend');
		$MoneyGoneModel = model('common/MoneyGone');
		$res = $RecommendModel->myRecommend($auth->member_id);
		// print_r($res);die;
		$totalRecomm = 0;
		foreach ($res as $key => &$value) {
			if(!empty($value)){
				$fuckData = $MoneyGoneModel->alias('g')->join('competition c','g.competition_id = c.competition_id')->where('c.member_id = ' . $value['member_id'] . ' and (g.type = 2 || g.type = 3 || g.type = 6)' . ' and g.member_id = ' . $auth->member_id)->sum('g.amount');
				$value['profit'] = sprintf("%.2f",round($fuckData,2));
				$totalRecomm += sprintf("%.2f",round($fuckData,2));
			}
		}

		return ['list' => $res, 'total' => count($res), 'total_rec' => $totalRecomm];
	}

	/**
	 * 我的反馈
	 */
	public function feedback($userInfo, $content)
	{
		$feedbackModel = model('common/Feedback');
		$data = [];
		$data['member_id'] = $userInfo['member_id'];
		$data['username'] = $userInfo['username'];
		$data['phone'] = $userInfo['phone'];
		$data['content'] = $content;
		$data['status'] = $feedbackModel::STATUS_UNTREATED;
		$data['remark'] = '';
		$data['create_time'] = time();
		return model('common/Feedback')->addData($data);
	}

	/**
	 * 编辑会员昵称
	 */
	public function editUserName($data, $auth = NULL)
	{
		$memberModel = model('common/Members');
		$memberInfo  = $memberModel->fetch(['member_id' => $auth->member_id]);
		if(empty($memberInfo)){
			exception(UserException::getErrorMsg(UserException::E_NOT_EXISTS), UserException::E_NOT_EXISTS, $this->_exceptions['user']);
		}

		return $memberModel->editData(['member_id' => $auth->member_id], $data);
	}

	/**
	 * 修改头像
	 */
	public function avatar($data, $auth = NULL)
	{
		$memberModel = model('common/Members');
		return $memberModel->editData(['member_id' => $auth->member_id], ['avatar' => $data]);
	}

	public function inventedLogin($auth = NULL, $type = 1)
	{
		$memberModel = model('common/Members');
		$auth = Auth::instance();
		if($type == 1){
			$memberInfo = $memberModel->fetch(['link_id' => $auth->member_id]);
			$userId = $auth->login($memberInfo['phone'], $memberInfo['password'], 1);
		}else{
			$memberInfo = $memberModel->fetch(['member_id' => $auth->link_id]);
			$userId = $auth->login($memberInfo['phone'], $memberInfo['password'], 1, 1);
		}

		if (!$userId) {
			exception(UserException::getErrorMsg(UserException::E_PASSWORD), UserException::E_PASSWORD, $this->_exceptions['user']);
		}

		// 生成JWT
		$token = Jwt::createToken($userId);
		if (!$token) {
			exception(UserException::getErrorMsg(UserException::E_JWT_ERROR), UserException::E_JWT_ERROR, $this->_exceptions['user']);
		}

		// 获取redis中的token
		$loginToken = Jwt::getColumn($token, 'uid');
		$updateId = UserModel::where('member_id', $memberInfo['member_id'])->update(['jwt_token' => $loginToken]);
		if ($updateId === false) {
			exception(UserException::getErrorMsg(UserException::E_JWT_ERROR), UserException::E_JWT_ERROR, $this->_exceptions['user']);
		}

		return ['auth' => $token, 'user_id' => $userId];
	}
}
